package cn.ecpay.unionpay.settle.Common;

import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.LogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 报文处理工具类
 * Created by zhaoyanzeng on 2018/11/7.
 */
public class CommonUtil {

    /**
     * 获取请求参数中所有的信息。
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParamStream(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        try {
            String notifyStr = new String(IOUtils.toByteArray(request.getInputStream()), CommonBase.encoding);
            LogUtil.writeLog("收到通知报文：" + notifyStr);
            JSONObject jObj = JSONObject.fromObject(notifyStr);
            for (Iterator<String> iter = jObj.keys(); iter.hasNext(); ) {
                String key = iter.next();
                String value = jObj.getString(key);
                res.put(key, value);
            }
        } catch (UnsupportedEncodingException e) {
            LogUtil.writeLog("getAllRequestParamStream.UnsupportedEncodingException error: " + e.getClass() + ":"
                    + e.getMessage());
        } catch (IOException e) {
            LogUtil.writeLog("getAllRequestParamStream.IOException error: " + e.getClass() + ":" + e.getMessage());
        }
        return res;
    }
}
